package com.sky.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sky.constant.MessageConstant;
import com.sky.exception.AddressBookBusinessException;
import com.sky.properties.SearchHttpAKProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.LinkedHashMap;
import java.util.Map;

@Component
public class SearchHttpAKUtil {

    @Autowired
    private SearchHttpAKProperties searchHttpAKProperties;
    //计算距离
    public static String URL_DISTANCE = "https://api.map.baidu.com/direction/v2/riding?";

    //获取坐标
    public static String URL_COORDINATE = "https://api.map.baidu.com/geocoding/v3?";

    /**
     * 获取两个坐标之间的距离
     *
     * @param shop
     * @param target
     * @return
     */
    public Integer getShopAddressAndTarget(String shop, String target) {
        //1、构造参数
        Map params = new LinkedHashMap<>();
        params.put("origin", shop);
        params.put("destination", target);
        params.put("ak", searchHttpAKProperties.getAK());
//        params.put("ak", searchHttpAKProperties.getAK());
        Integer distance = null;
        //2、发送请求获取结果
        try {
            String message = requestGetAK(URL_DISTANCE, params);
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readTree(message);

            // 提取 distance
            distance = root.path("result")
                    .path("routes")
                    .get(0)  // 获取 routes 数组的第一个元素
                    .path("distance")
                    .asInt();
            Integer.valueOf(distance);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        distance = distance / 1000;
        return distance;
    }

    /**
     * 单独获取商店的
     *
     * @return
     */
    public String getShopAddress() {
        String shopAddressCoordinate = getShopAddressCoordinate(searchHttpAKProperties.getAddress());
        return shopAddressCoordinate;
    }

    /**
     * 输入地址, 获取地址坐标
     *
     * @param address
     * @return
     */

    public String getShopAddressCoordinate(String address) {
        //构造参数
        Map params = new LinkedHashMap<>();
        params.put("address", address);
        params.put("output", "json");
        params.put("ak", searchHttpAKProperties.getAK());
        params.put("callback", "showLocation");
        String formattedLng = null;
        String formattedLat = null;

        try {
            String response = requestGetAK(URL_COORDINATE, params);
            String jsonStr = response.substring(response.indexOf("(") + 1, response.lastIndexOf(")"));
            // 2. 使用 Jackson 解析 JSON
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(jsonStr);
            //lng = rootNode.path("result").path("location").path("lng").toString();
            //lat = rootNode.path("result").path("location").path("lat").toString();
            double lng = rootNode.path("result").path("location").path("lng").asDouble();
            double lat = rootNode.path("result").path("location").path("lat").asDouble();
            DecimalFormat df = new DecimalFormat("#.######");  // 保留6位小数
            formattedLng = df.format(lng);
            formattedLat = df.format(lat);
            System.out.println(formattedLng + "=================" + formattedLat);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (formattedLat == null || formattedLat == null) {
            throw new AddressBookBusinessException(MessageConstant.UNKNOWN_ERROR);
        }
        String coordinate = formattedLat + "," + formattedLng;
        return coordinate;
    }

    /**
     * ----------------------> 发送请求的方法
     * 默认ak
     * 选择了ak，使用IP白名单校验：
     * 根据您选择的AK已为您生成调用代码
     * 检测到您当前的ak设置了IP白名单校验
     * 您的IP白名单中的IP非公网IP，请设置为公网IP，否则将请求失败
     * 请在IP地址为xxxxxxx的计算发起请求，否则将请求失败
     */
    public String requestGetAK(String strUrl, Map<String, String> param) throws Exception {
        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return null;
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            //    第一种方式使用的 jdk 自带的转码方式  第二种方式使用的 spring 的转码方法 两种均可
            //    queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8").replace("+", "%20") + "&");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        System.out.println(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();
//        System.out.println("AK: " + buffer.toString());
        return buffer.toString();
    }


}
